package com.dalei.vds;

import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Locale;

import com.dalei.vds.dao.ModelDao;
import com.dalei.vds.environment.CurrentTask;
import com.dalei.vds.soap.DetectionSoapImpl;
import com.dalei.vdserver.shared.model.ErrorCode;
import com.dalei.vdserver.shared.model.VehicleInformation;
import com.dalei.vdserver.shared.soap.DetectionSoap;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class ConfirmActivity extends Activity {

	public static final int REQUEST_DETECTION = 0x00000030;
	
	private static final int MESSAGE_SHOW_PROGRESS_DIALOG = 0x00000000;

	private static final int MESSAGE_DISMISS_PROGRESS_DIALOG = 0x00000001;

	private static final int MESSAGE_SHOW_TOAST = 0x00000002;

	private static final int MESSAGE_LOAD_INFORMATION = 0x00000006;
	
	private TextView plateNumberText;

	private TextView plateTypeText;

	private TextView vinText;

	private TextView vehicleTypeText;

	private TextView brandAndModelText;

	private TextView bodyColorText;

	private TextView engineModelText;

	private TextView fuelTypeText;

	private TextView ownersText;

	private TextView regDateText;

	private Button confirmBtn;

	private Button cancelBtn;

	private Handler handler;

	private Dialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.confirm);

		handler = new IncomingHandler(this);

		plateNumberText = (TextView) findViewById(R.id.confirm_text_plate_number);
		plateTypeText = (TextView) findViewById(R.id.confirm_text_plate_type);
		vinText = (TextView) findViewById(R.id.confirm_text_vin);
		vehicleTypeText = (TextView) findViewById(R.id.confirm_text_vehicle_type);
		brandAndModelText = (TextView) findViewById(R.id.confirm_text_brand_and_model);
		bodyColorText = (TextView) findViewById(R.id.confirm_text_body_color);
		engineModelText = (TextView) findViewById(R.id.confirm_text_engine_model);
		fuelTypeText = (TextView) findViewById(R.id.confirm_text_fuel_type);
		ownersText = (TextView) findViewById(R.id.confirm_text_owners);
		regDateText = (TextView) findViewById(R.id.confirm_text_reg_date);

		confirmBtn = (Button) findViewById(R.id.confirm_btn_confirm);
		confirmBtn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(ConfirmActivity.this, DetectionActivity.class);
				startActivityForResult(intent, REQUEST_DETECTION);
			}
		});

		cancelBtn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (CurrentTask.isTaskLocked()) {
					Thread thread = new UnlockTaskThread(ConfirmActivity.this);
					thread.start();
					while (thread.isAlive()) {

					}
				}
				CurrentTask.setFid(-1);
				CurrentTask.setTaskLocked(false);
				CurrentTask.setVehicleInformation(null);
				setResult(RESULT_CANCELED);
				finish();
			}
		});

		Thread thread = new OnLoadThread(this);
		thread.start();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case REQUEST_DETECTION:
			switch (resultCode) {			
			case DetectionActivity.RESULT_OK:
				setResult(RESULT_OK);
				break;
				
			case DetectionActivity.RESULT_CANCELED:
				Thread thread = new UnlockTaskThread(this);
				thread.start();
				while (thread.isAlive()) {

				}
				setResult(RESULT_CANCELED);
				break;
			
			default:
				break;
			}
			
			CurrentTask.setFid(-1);
			CurrentTask.setTaskLocked(false);
			CurrentTask.setVehicleInformation(null);
			CurrentTask.setInvalidItems(null);
			CurrentTask.setImages(null);
			CurrentTask.setOdometerReading(-1);
			CurrentTask.setNotes(null);
			
			finish();
			break;

		default:
			break;
		}
	}

	private static class IncomingHandler extends Handler {

		private WeakReference<ConfirmActivity> reference;

		public IncomingHandler(ConfirmActivity activity) {
			// TODO Auto-generated constructor stub
			reference = new WeakReference<ConfirmActivity>(activity);
		}

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			final ConfirmActivity activity = reference.get();

			switch (msg.what) {
			case MESSAGE_SHOW_PROGRESS_DIALOG:
				activity.dialog = ProgressDialog.show(activity, null,
						activity.getString(R.string.waitting));
				break;

			case MESSAGE_DISMISS_PROGRESS_DIALOG:
				activity.dialog.dismiss();
				break;

			case MESSAGE_SHOW_TOAST:
				Toast.makeText(activity, activity.getString(msg.arg1),
						Toast.LENGTH_SHORT).show();
				break;

			case MESSAGE_LOAD_INFORMATION:
				VehicleInformation vi = (VehicleInformation) msg.obj;

				if (vi.getLicensePlateNumber() != null) {
					activity.plateNumberText
							.setText(vi.getLicensePlateNumber());
				} else {
					activity.plateNumberText.setText(activity
							.getString(R.string.not_available));
				}

				ModelDao modelDao = new ModelDao(activity);

				String licensePlateType = modelDao.getLicensePlateTypeName(vi
						.getLicensePlateType());
				if (licensePlateType != null) {
					activity.plateTypeText.setText(licensePlateType);
				} else {
					activity.plateTypeText.setText(activity
							.getString(R.string.not_available));
				}

				if (vi.getVin() != null) {
					activity.vinText.setText(vi.getVin());
				} else {
					activity.vinText.setText(activity
							.getString(R.string.not_available));
				}

				String vehicleType = modelDao.getVehicleTypeName(vi
						.getVehicleType());
				if (vehicleType != null) {
					activity.vehicleTypeText.setText(vehicleType);
				} else {
					activity.vehicleTypeText.setText(activity
							.getString(R.string.not_available));
				}

				if (vi.getBrandAndModel() != null) {
					activity.brandAndModelText.setText(vi.getBrandAndModel());
				} else {
					activity.brandAndModelText.setText(activity
							.getString(R.string.not_available));
				}

				String bodyColor = modelDao.getBodyColorName(vi.getBodyColor());
				if (bodyColor != null) {
					activity.bodyColorText.setText(bodyColor);
				} else {
					activity.bodyColorText.setText(activity
							.getString(R.string.not_available));
				}

				if (vi.getEngineModel() != null) {
					activity.engineModelText.setText(vi.getEngineModel());
				} else {
					activity.engineModelText.setText(activity
							.getString(R.string.not_available));
				}

				String fuelType = modelDao.getFuelTypeName(vi.getFuelType());
				if (fuelType != null) {
					activity.fuelTypeText.setText(fuelType);
				} else {
					activity.fuelTypeText.setText(activity
							.getString(R.string.not_available));
				}

				if (vi.getOwners() != null) {
					activity.ownersText.setText(vi.getOwners());
				} else {
					activity.ownersText.setText(activity
							.getString(R.string.not_available));
				}

				if (vi.getRegistrationDate() != null) {
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
							"yyyy/MM/dd HH:mm:ss", Locale.CHINA);
					String registrationDate = simpleDateFormat.format(vi
							.getRegistrationDate());
					activity.regDateText.setText(registrationDate);
				} else {
					activity.regDateText.setText(activity
							.getString(R.string.not_available));
				}

				break;

			default:
				break;
			}
		}
	}

	private class OnLoadThread extends Thread {

		private ConfirmActivity activity;

		public OnLoadThread(ConfirmActivity activity) {
			// TODO Auto-generated constructor stub
			this.activity = activity;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			Message msg = null;
			if (CurrentTask.getFid() > 0) {
				activity.handler.sendEmptyMessage(MESSAGE_SHOW_PROGRESS_DIALOG);

				DetectionSoap detectionSoap = new DetectionSoapImpl(activity);
				int result = detectionSoap.lockDetectionTask(CurrentTask.getFid());
				if (result > 0) {
					VehicleInformation vi = detectionSoap
							.getVehicleInformation(CurrentTask.getFid());
					if (vi != null) {
						CurrentTask.setTaskLocked(true);
						CurrentTask.setVehicleInformation(vi);

						msg = activity.handler.obtainMessage();
						msg.what = MESSAGE_LOAD_INFORMATION;
						msg.obj = vi;
						activity.handler.sendMessage(msg);

						activity.handler
								.sendEmptyMessage(MESSAGE_DISMISS_PROGRESS_DIALOG);
					} else {
						activity.handler
								.sendEmptyMessage(MESSAGE_DISMISS_PROGRESS_DIALOG);

						msg = activity.handler.obtainMessage();
						msg.what = MESSAGE_SHOW_TOAST;
						msg.arg1 = R.string.get_vehicle_information_failed_err;
						activity.handler.sendMessage(msg);
					}
				} else {
					activity.confirmBtn.setEnabled(false);
					activity.handler
							.sendEmptyMessage(MESSAGE_DISMISS_PROGRESS_DIALOG);

					msg = activity.handler.obtainMessage();
					msg.what = MESSAGE_SHOW_TOAST;

					switch (result) {
					case ErrorCode.UNKNOW_ERROR:
						msg.arg1 = R.string.unknow_error;
						break;

					case ErrorCode.INTERNAL_ERROR:
						msg.arg1 = R.string.internal_error;
						break;

					case ErrorCode.Detection.GET_TASK_FAILED:
						msg.arg1 = R.string.get_task_failed_err;
						break;

					case ErrorCode.Detection.TASK_ALREADY_LOCKED:
						msg.arg1 = R.string.task_already_locked_err;
						break;

					default:
						msg.arg1 = R.string.default_value;
						break;
					}

					activity.handler.sendMessage(msg);
				}
			} else {
				activity.confirmBtn.setEnabled(false);
				msg = activity.handler.obtainMessage();
				msg.what = MESSAGE_SHOW_TOAST;
				msg.arg1 = R.string.invalid_fid_err;
				activity.handler.sendMessage(msg);
			}
		}
	}

	private class UnlockTaskThread extends Thread {

		private ConfirmActivity activity;

		public UnlockTaskThread(ConfirmActivity activity) {
			// TODO Auto-generated constructor stub
			this.activity = activity;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			activity.handler.sendEmptyMessage(MESSAGE_SHOW_PROGRESS_DIALOG);
			DetectionSoap detectionSoap = new DetectionSoapImpl(activity);
			int result = detectionSoap.unlockDetectionTask(CurrentTask.getFid());
			activity.handler.sendEmptyMessage(MESSAGE_DISMISS_PROGRESS_DIALOG);
			Message msg = activity.handler.obtainMessage();
			msg.what = MESSAGE_SHOW_TOAST;
			if (result > 0) {
				msg.arg1 = R.string.free_task;
			} else {
				switch (result) {
				case ErrorCode.UNKNOW_ERROR:
					msg.arg1 = R.string.unknow_error;
					break;

				case ErrorCode.INTERNAL_ERROR:
					msg.arg1 = R.string.internal_error;
					break;

				case ErrorCode.Detection.GET_TASK_FAILED:
					msg.arg1 = R.string.get_task_failed_err;
					break;

				case ErrorCode.Detection.TASK_ALREADY_UNLOCKED:
					msg.arg1 = R.string.task_already_unlocked_err;
					break;

				default:
					msg.arg1 = R.string.default_value;
					break;
				}
			}
			activity.handler.sendMessage(msg);
		}
	}
}
